package com.teichmann.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

public class ConnectionUtils {

	static HttpClient client = null;
	
	public static HttpClient getClient(){
		HttpParams httpParams = new BasicHttpParams();
		if (client == null) {
         System.out.println("client is null. Instantiating... ");
         client = new DefaultHttpClient();
      }
		
		return client;

	}
	
	
	/**
	 * @param url
	 * @return String Html content
	 * @throws Exception
	 */
	public static String get(String url) throws IOException {
		
		client =getClient();
		HttpGet method = new HttpGet(url);

		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		return client.execute(method, responseHandler);
	}

	public static String post(String value, Map parameters) throws IOException {
		HttpParams httpParams = new BasicHttpParams();
		List<NameValuePair> param = new ArrayList<NameValuePair>();

		Iterator it = parameters.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
			httpParams.setParameter(pairs.getKey(), pairs.getValue());
			param.add(new BasicNameValuePair(pairs.getKey(), pairs.getValue()));
			System.out.println(pairs.getKey() + " = " + pairs.getValue());
		}
		client =getClient();

		HttpPost method = new HttpPost(value);
		UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(param, HTTP.UTF_8);
		method.setEntity(sendentity);

		// Execute the method.
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String response = client.execute(method, responseHandler);

		return response;
	}

}
